//
//  AuthInfoViewController.swift
//  MintBag
//
//  Created by wy on 2024/9/18.
//

import UIKit
import CoreLocation

class AuthInfoViewController: UIViewController {
    
    @IBOutlet weak var contactsLabel: UILabel!
    @IBOutlet weak var locationLabel: UILabel!
    @IBOutlet weak var cameraLabel: UILabel!
    @IBOutlet weak var contactsBtn: UIButton!
    @IBOutlet weak var locationBtn: UIButton!
    @IBOutlet weak var cameraBtn: UIButton!
    
    var locationManager: CLLocationManager!
    var contactsDenied: Bool = false
    var locationDenied: Bool = false
    var photoDenied: Bool = false
    var cameraDenied: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        
//        locationManager = CLLocationManager()
//        locationManager.delegate = self
//        locationManager.desiredAccuracy = kCLLocationAccuracyBest
//
//        checkContactsPermission()
//        checkLocationPermission()
//        checkCameraPermission()
    }
    
    func checkContactsPermission() {
        AuthTools.checkContactsPermission { status in
            if status == .denied {
                contactsDenied = true
            }else if status == .authorized {
                contactsLabel.textColor = .init(hex: "#FF5500")
                contactsBtn.isSelected = true
            }
        }
    }
    
    func checkLocationPermission() {
        AuthTools.checkLocationPermission { status in
            if status == .denied {
                locationDenied = true
            }else if status == .authorized {
                locationLabel.textColor = .init(hex: "#FF5500")
                locationBtn.isSelected = true
            }
        }
    }
    
    func checkCameraPermission() {
        AuthTools.checkCameraPermission { status in
            if status == .denied {
                cameraDenied = true
            }else if status == .authorized {
                cameraLabel.textColor = .init(hex: "#FF5500")
                cameraBtn.isSelected = true
            }
        }
    }
    
    func applyContactsAuth() {
        AuthTools.applyContactsAuth { [weak self] status in
            if status == .authorized {
                self?.contactsLabel.textColor = .init(hex: "#FF5500")
                self?.contactsBtn.isSelected = true
            }
        }
    }
    
    func applyCameraAuth() {
        AuthTools.applyCameraAuth { [weak self] status in
            if status == .authorized {
                self?.cameraLabel.textColor = .init(hex: "#FF5500")
                self?.cameraBtn.isSelected = true
            }
        }
    }
    
    func showSettingAlert() {
        let alert = UIAlertController(title: nil, message: "Permission has been disabled. Do you want to go to the settings to enable permission？", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Go set it up", style: .default, handler: { _ in
            if let setting = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(setting, options: [:], completionHandler: nil)
            }
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        present(alert, animated: true)
    }
    
    @IBAction func actionBack(_ sender: Any) {
        dismiss(animated: true)
    }
    
    @IBAction func actionContacts(_ sender: Any) {
        if contactsBtn.isSelected { return }
        if contactsDenied {
            showSettingAlert()
            return
        }
        applyContactsAuth()
    }
    
    @IBAction func actionLocation(_ sender: Any) {
        if locationBtn.isSelected { return }
        if locationDenied {
            showSettingAlert()
            return
        }
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }
    
    @IBAction func actionCamera(_ sender: Any) {
        if cameraBtn.isSelected { return }
        if cameraDenied {
            showSettingAlert()
            return
        }
        applyCameraAuth()
    }
    
}

extension AuthInfoViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        locationLabel.textColor = .init(hex: "#FF5500")
        locationBtn.isSelected = true
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {

    }
}

extension UIColor {
    convenience init(hex: String) {
        var hexString: String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

        if hexString.hasPrefix("#") {
            hexString.remove(at: hexString.startIndex)
        }

        if hexString.count != 6 {
            self.init(white: 1.0, alpha: 0.0)
            return
        }

        var rgbValue: UInt64 = 0
        Scanner(string: hexString).scanHexInt64(&rgbValue)

        let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
        let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
        let blue = CGFloat(rgbValue & 0x0000FF) / 255.0

        self.init(red: red, green: green, blue: blue, alpha: 1.0)
    }
}

